package ckR

import (
	"db2s/Er"
	metaD "db2s/MetaInit"
	"db2s/arg"
	cp "db2s/componentInit"
	"db2s/global"
	"db2s/outPut"
	"db2s/parDef"
	"db2s/pubM"
	quit "db2s/quitDispos"
	mq "db2s/topic-mq"
	"github.com/panjf2000/ants/v2"
	"os"
	"reflect"
	"sync"
	"time"
)

type (
	schemaInitContext SchemaInitContext
	// Topic 自定义Topic 类型 限制范围 避免出错
	Topic string
	Logo  string //dataFix Type 标识
	// CheckObject 自定义CheckObject 类型 限制范围 避免出错
	CheckObject string
	CheckMode   string // CheckMode
	IndexType   string //Index type distinction
	Keywords    string //data split keyword
)

// count index check topic
const (
	CountWay                 Topic = "CountWay"
	CountPoint               Topic = "CountPoint"
	CountIndexSegmentQuery   Topic = "CountIndexSegmentQuery"
	CountIndexSecondQuerySql Topic = "CountIndexSecondQuerySql"
	CountIndexQueryData      Topic = "CountIndexQueryData"
	CountIndexResult         Topic = "CountIndexResult"
)

// rows index check topic
const (
	IsMode               Topic = "IsMode"
	IsSegmentQuery       Topic = "IsSegmentQuery"
	IndexConcurrentQuery Topic = "IndexConcurrentQuery"
	QueryTableSql        Topic = "QueryTableSql"
	QueryTableData       Topic = "QueryTableData"
	Md5Rows              Topic = "Md5Rows"
	Arrcmp               Topic = "Arrcmp"
	AbnormalDataDiff     Topic = "AbnormalDataDiff"
	DataFixDiff          Topic = "DataFixDiff"
)
const (
	rowsMissSegmentQuery     Topic = "rowsMissSegmentQuery"
	RowsMissMd5              Topic = "RowsMissMd5"
	RowsMissArrcmp           Topic = "RowsMissArrcmp"
	RowsMissMd5ValueUniq     Topic = "RowsMissMd5ValueUniq"
	RowsMissAbnormalDataDiff Topic = "RowsMissAbnormalDataDiff"
	RowsMissDataGeneralSql   Topic = "RowsMissDataGeneralSql"
	RowsMissDataValueRead    Topic = "RowsMissDataValueRead"
	RowsMissFixSqlExec       Topic = "RowsMissFixSqlExec"
)

// splist
const (
	SdriveSql        Keywords  = "/*sdrive*/"
	DdriveSql        Keywords  = "/*ddrive*/"
	RowsDataSplict   Keywords  = "/*go actions rowData*/"
	ColumnDataSplict Keywords  = "/*go actions columnData*/"
	Linsert          Logo      = "/*insertS*/"
	Ldelete          Logo      = "/*deleteS*/"
	Ipri             IndexType = "pri"
	Iuni             IndexType = "uni"
	Imui             IndexType = "mui"
	AbnormalSql      Keywords  = "/*abnormalSql*/"
)

var (
	lock                    sync.Mutex
	SchemaContext           *schemaInitContext
	PlanContext             *SchedulePlanContext
	GlobalPConfigs          *GlobalParametersConfig
	closeObject             quit.Close
	ResultStatisticsMq      chan any
	BarResultStatisticMq    chan any
	ResultStatisticsGeneral ResultGeneral
	//producer 生产者
	producer mq.Producer
	//consumer 消费者
	consumer                mq.Consumer
	FuncRef                 map[string]reflect.Value
	ScheduleTaskInitFuncRef map[string]reflect.Value
	MqListenerSInitFunc     map[string]reflect.Value
	terminalPods            chan *global.TPod
)

type (
	RowsMissReadAbnormalDataFormat struct {
		Action   string
		Md5Value string
		RowsData *string
	}
	SchemaInitContextConfig struct {
		TableList     []string            //表对象清单
		GtCheckConfig arg.ConfigParameter //客户端传参
	}
	// GlobalISObject 全局表结构或结构初始化对象
	GlobalISObject struct {
		TableMetaData map[string]Er.TablesMetaInfoEr
	}
	querySql struct {
		Source string `json:"source"`
		Dest   string `json:"dest"`
	}
	FixSql struct {
		Delete []any `json:"delete"`
		Insert []any `json:"insert"`
		LobS   bool
	}
	sqlData struct {
		Source any
		Dest   any
		Ssum   int64
		Dsum   int64
	}
	GlobalParametersConfig struct { // SchedulePlanConfig 输入参数重新复制
		FilePoint ReadWriteFilePointS
		repair    arg.RepairS
		result    arg.Result
		rules     arg.RulesS
		dSns      arg.DSNsS
		structs   arg.StructS
		db        pubM.Conn
	}
	TableMetaDataDispos struct {
		LogThreadSeq  int64
		schemaStrconv global.TableMapStrconv
		tableStrconv  global.TableMapStrconv
	}
	CheckSchemaMetaData struct {
		TableMD               []*metaD.TableMeta
		TableObject           []*arg.InputTableAttributes
		TableObjectFlow       chan any
		ObjectSum             int
		IgnoreObjectSum       int64
		schemaMetaMsgSendBody *mq.MonitorMsgMq
	}
	SchedulePlanContextConfig struct {
		TableList     []string
		BeginTime     time.Time
		GtCheckConfig arg.ConfigParameter
		MQConfig      *cp.MQConfig
	}
	TableAllColumnInfoS struct {
		SColumnInfo    []map[string]string //表的所有列信息
		DColumnInfo    []map[string]string //表的所有列信息
		Schema         string
		Table          string
		IndexColumnSeq map[string]string
		ColumnSeq      map[string]string
		MapTable       map[string]string
		IndexType      string
		IndexColumn    []string
		SshardName     string
		DshardName     string
	}

	Animal struct {
		Key string
		Val string
	}
	FileOperate struct {
		tmpDataFileF    *os.File
		tmpDataFileName string
		tmpMd5FileF     *os.File
		tmpMd5FileName  string
	}
	Object struct {
		TaskSeq         int    //表校验序号
		ObjectLogSeq    int64  //表对象的日志号
		TableMiss       bool   //表是否存在
		Schema, Table   string //check schema Name and check table Name
		MSchema, MTable string //map check schema name and check table name
		RowsLimit       int    //限制表的查询/迁移行数
		TableJoin       string
		Role            string
		PartName        []string
	}
	tabBaseMe struct {
		Col   any `json:"struct"`
		Index any `json:"index"`
		Part  any `json:"part"`
	}
	// SchedulePlan2 执行计划操作对象
	SchedulePlan2 struct {
		Object            Object
		SrcParameter      parDef.Parameter
		DstParameter      parDef.Parameter
		baseMe            tabBaseMe
		MQ                *mq.MonitorMsgMq
		ReadOptimizer     global.ReadOptimizer
		repair            arg.RepairS
		rules             arg.RulesS
		statistics        global.Statistics
		writeOptimizer    global.WriteOptimizer
		TableLocNumber    uint64
		Status            global.TableStatus
		subTaskInfo       *mq.SubTasks
		rows              global.RowsPlan
		count             global.CountPlan
		TPod              *outPut.TPod
		XlsTerminal       *outPut.WorkSheetTerminal
		XlsResult         *outPut.WorkSheetResult
		XlsMiss           *outPut.WorkSheetMiss
		SpeedLimitMonitor *mq.SpeedLimitMonitor
		TableAttributes   arg.TableSubOptions
	}

	// SchedulePlanContext 执行计划上下文
	SchedulePlanContext struct {
		//多任务执行计划
		ChanSchedulePlanTable chan any //[]map[string] /*SchemaToTable*/ *SchedulePlan2
		//存储执行计划任务
		SchedulePlanTable any //map[string] /*SchemaToTable*/ *SchedulePlan2
		// 上下文任务线程池
		Pool *ants.Pool
		//自动关闭mq的组件
		AutoCloseMqComponentTable map[cp.CheckMode]*cp.AutoCloseMqComponent
		//进度条
		TaskBarTable *mq.TaskBar
		Rw           sync.Mutex
		BeginTime    time.Time
		wg           sync.WaitGroup
		//TableMiss    chan TableObjectMiss
	}
	// SchemaInitContext 执行计划上下文
	SchemaInitContext struct {
		Seq               int
		Schema            string
		Table             string
		MSchema           string
		MTable            string
		TableMiss         bool
		ObjectLogSeq      int64
		TColumnMeta       global.TableMetaGather
		IndexData         metaD.IndexChooseResult
		Role              string
		TableSum          int
		IgnoreObjectSum   int64
		TableFree         *int64
		TableAccount      *int64
		BreakPointSum     *int64
		TableAttributes   arg.TableSubOptions
		Meta              global.TableMetaS
		BaseMe            tabBaseMe
		Options           parDef.Options
		ChanSchemaContext chan any //chan *SchemaInitContext
		TPod              *outPut.TPod
	}
	AutoCloseMqComponent struct {
		TopicStatistics  map[Topic]*int64
		UnsubscribeTopic []Topic
		CheckMode        CheckMode
		EndMark          bool
	}
)
